/**
 * 管理 user 功能模块的相关状态的vuex数据
 */
import {
  reqAutoLogin,
} from '../../api'
import {
  RECEIVE_USER,
  RESET_USER,
  RECEIVE_TOKEN,
  RESET_TOKEN,
} from '../mutations-types'

const state = {
  user: {}, // 登录的用户
  token: localStorage.getItem("token_key"),
}

const mutations = {
  [RECEIVE_USER](state, user) {
    state.user = user
  },
  [RECEIVE_TOKEN](state, token) {
    state.token = token
  },
  [RESET_USER](state) {
    state.user = {}
  },
  [RESET_TOKEN](state) {
    state.token = []
  },
}

const actions = {
  // 同步登录请求
  saveUser({
    commit
  }, user) {
    // 从user中提取token
    const token = user.token
    localStorage.setItem("token_key", token)

    commit(RECEIVE_TOKEN, token)

    // 删除user的token
    delete user.token
    // 提交到mutations中
    commit(RECEIVE_USER, user)
  },

  // 同步退出登录
  resetUser({
    commit
  }) {
    commit(RESET_USER)
    commit(RESET_TOKEN)
    localStorage.removeItem("token_key")
  },

  //  异步获取用户信息
  async autoLogin({
    commit,
    state
  }) {
    if (state.token) {
      const result = await reqAutoLogin()
      // console.log(result)
      if (result.code === 0) {
        const user = result.data
        commit(RECEIVE_USER, user)
      }
    }
  },
}
const getters = {}

export default {
  state,
  mutations,
  actions,
  getters
}
